#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.web as torweb
import tornado.ioloop as toriol
import omen.tools.configuration as conf
import web_xtrack.web_const as w_const
import omen.connectors.mongodb as mongob
import pymongo
import web_xtrack.web_handlers as xtrack_handler

# check connection with database
def check_data_connection():
    try:
        w_const.DATABASE_CONNECTION = mongob.SafeMongoClient()
        return w_const.DATABASE_CONNECTION.alive()
    except pymongo.errors.ConnectionFailure:
        return False

if __name__ == '__main__':
    # get configuration
    w_const.CONFIGURATION = conf.JSONConf.load_from_file('../conf/configuration.json')
    
    w_const.template_default_dico['ajout_inter'] = {'users': w_const.CONFIGURATION['user_list'], 'kits': w_const.CONFIGURATION['ek_list']}
    w_const.template_default_dico['search_inter'] = {'users': w_const.CONFIGURATION['user_list'], 'kits': w_const.CONFIGURATION['ek_list']}
    
    while not check_data_connection():
        print ("Connection Error to the database, check the database ...")

    
    # application
    application = torweb.Application(handlers=[
        (r'/xtrack', xtrack_handler.XTrackHandler), 
        (r'/xtrack/intervention', xtrack_handler.ViewInter)],
        template_path='../templates',
        static_path='../static')
    application.listen(8010)
    
    # starting loop
    toriol.IOLoop.instance().start()